/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package PRESENT;

import UTILS.ErrorMessages;
import UTILS.StatusMessage;
import UTILS.GUIConstant;
import BUS.LoaiDaiLyBUS;
import DTO.LoaiDaiLyDTO;
import DTO.TinhDTO;
import UTILS.IDATAGUI;
import UTILS.IInitGUI;
import UTILS.IStateGUI;
import UTILS.ITableGUI;
import UTILS.SelectTableDialog;
import UTILS.ToolOfGUI;
import java.awt.event.ActionEvent;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import javax.swing.AbstractAction;
import javax.swing.JComponent;
import javax.swing.KeyStroke;
import javax.swing.table.DefaultTableModel;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;


/**
 *
 * @author HuuTri
 */
public class LoaiDaiLyGUI extends javax.swing.JFrame
                     implements IDATAGUI, IInitGUI, IStateGUI, ITableGUI {

    LoaiDaiLyGUIState currState;
    
    /**
     * Creates new form LoaiDaiLyGUI
     */
    public LoaiDaiLyGUI() {
        initComponents();
        initCustom();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jSplitPane1 = new javax.swing.JSplitPane();
        panelButton = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        txtTenLoaiDaiLy_Error = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jScrollPane3 = new javax.swing.JScrollPane();
        txtMoTa = new javax.swing.JTextArea();
        txtTenLoaiDaiLy = new javax.swing.JTextField();
        txtMaLoaiDaiLy = new javax.swing.JTextField();
        btnXoaBo = new javax.swing.JButton();
        btnLuuLai = new javax.swing.JButton();
        btnThemMoi = new javax.swing.JButton();
        txtId = new javax.swing.JTextField();
        jLabel6 = new javax.swing.JLabel();
        txtMaLoaiDaiLy_Error = new javax.swing.JLabel();
        jPanel2 = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        tableLoaiDaiLy = new org.jdesktop.swingx.JXTable();
        txtStatus = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setMinimumSize(new java.awt.Dimension(800, 600));

        jSplitPane1.setBorder(javax.swing.BorderFactory.createTitledBorder(""));
        jSplitPane1.setDividerLocation(320);
        jSplitPane1.setAutoscrolls(true);
        jSplitPane1.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        jSplitPane1.setMinimumSize(new java.awt.Dimension(0, 0));
        jSplitPane1.setPreferredSize(new java.awt.Dimension(0, 0));

        panelButton.setForeground(new java.awt.Color(255, 51, 51));
        panelButton.setFont(new java.awt.Font("Times New Roman", 0, 13)); // NOI18N

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 13)); // NOI18N
        jLabel1.setText("Mã Loại Đại Lý(*): ");

        jLabel2.setFont(new java.awt.Font("Tahoma", 1, 13)); // NOI18N
        jLabel2.setText("Tên Loại Đại Lý(*): ");

        txtTenLoaiDaiLy_Error.setFont(new java.awt.Font("Times New Roman", 0, 13)); // NOI18N
        txtTenLoaiDaiLy_Error.setForeground(new java.awt.Color(255, 51, 51));

        jLabel3.setFont(new java.awt.Font("Tahoma", 1, 13)); // NOI18N
        jLabel3.setText("Mô tả: ");

        txtMoTa.setColumns(20);
        txtMoTa.setFont(new java.awt.Font("Tahoma", 0, 13)); // NOI18N
        txtMoTa.setLineWrap(true);
        txtMoTa.setRows(5);
        txtMoTa.setDebugGraphicsOptions(javax.swing.DebugGraphics.NONE_OPTION);
        jScrollPane3.setViewportView(txtMoTa);

        txtTenLoaiDaiLy.setFont(new java.awt.Font("Tahoma", 0, 13)); // NOI18N
        txtTenLoaiDaiLy.setDebugGraphicsOptions(javax.swing.DebugGraphics.NONE_OPTION);
        txtTenLoaiDaiLy.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                txtTenLoaiDaiLyFocusLost(evt);
            }
        });

        txtMaLoaiDaiLy.setFont(new java.awt.Font("Tahoma", 0, 13)); // NOI18N
        txtMaLoaiDaiLy.setDebugGraphicsOptions(javax.swing.DebugGraphics.NONE_OPTION);
        txtMaLoaiDaiLy.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                txtMaLoaiDaiLyFocusLost(evt);
            }
        });
        txtMaLoaiDaiLy.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                txtMaLoaiDaiLyKeyTyped(evt);
            }
        });
        txtMaLoaiDaiLy.setDocument(new PlainDocument() {
            public void insertString(int offset, String str, AttributeSet attr) throws BadLocationException {
                if (str == null)
                return;
                str = str.toUpperCase();
                if ((getLength() + str.length()) <= GUIConstant.LOAIDAILY_MALOAIDAILY_LENGTH_MAX) {
                    super.insertString(offset, str, attr);
                } else {
                    txtMaLoaiDaiLy_Error.setText(ErrorMessages.LOAIDAILYGUI_TXTMALOAIDAILY_ERROR_GREATER +
                        GUIConstant.LOAIDAILY_MALOAIDAILY_LENGTH_MAX);
                }
            }
        });

        btnXoaBo.setText("Xóa Bỏ");
        btnXoaBo.setToolTipText("CTRL + DELETE");
        btnXoaBo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnXoaBoActionPerformed(evt);
            }
        });

        btnLuuLai.setText("Lưu Lại");
        btnLuuLai.setToolTipText("CTRL + S");
        btnLuuLai.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnLuuLaiActionPerformed(evt);
            }
        });

        btnThemMoi.setText("Thêm Mới");
        btnThemMoi.setToolTipText("CTRL + N");
        btnThemMoi.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnThemMoiActionPerformed(evt);
            }
        });

        txtId.setEditable(false);

        jLabel6.setFont(new java.awt.Font("Tahoma", 1, 13)); // NOI18N
        jLabel6.setText("Số định danh: ");

        txtMaLoaiDaiLy_Error.setFont(new java.awt.Font("Times New Roman", 0, 13)); // NOI18N
        txtMaLoaiDaiLy_Error.setForeground(new java.awt.Color(255, 0, 0));

        javax.swing.GroupLayout panelButtonLayout = new javax.swing.GroupLayout(panelButton);
        panelButton.setLayout(panelButtonLayout);
        panelButtonLayout.setHorizontalGroup(
            panelButtonLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panelButtonLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(panelButtonLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(txtMaLoaiDaiLy_Error, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(panelButtonLayout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(btnThemMoi)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnLuuLai)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnXoaBo))
                    .addComponent(txtMaLoaiDaiLy)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panelButtonLayout.createSequentialGroup()
                        .addGroup(panelButtonLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jScrollPane3)
                            .addComponent(txtTenLoaiDaiLy, javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, panelButtonLayout.createSequentialGroup()
                                .addGroup(panelButtonLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel1)
                                    .addComponent(jLabel3)
                                    .addComponent(jLabel2)
                                    .addComponent(jLabel6)
                                    .addComponent(txtId, javax.swing.GroupLayout.PREFERRED_SIZE, 69, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addGap(0, 172, Short.MAX_VALUE))
                            .addComponent(txtTenLoaiDaiLy_Error, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addGap(6, 6, 6))))
        );
        panelButtonLayout.setVerticalGroup(
            panelButtonLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panelButtonLayout.createSequentialGroup()
                .addComponent(jLabel6)
                .addGap(7, 7, 7)
                .addComponent(txtId, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel1)
                .addGap(8, 8, 8)
                .addComponent(txtMaLoaiDaiLy, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(txtMaLoaiDaiLy_Error)
                .addGap(12, 12, 12)
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(txtTenLoaiDaiLy, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(txtTenLoaiDaiLy_Error)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel3)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 288, Short.MAX_VALUE)
                .addGap(35, 35, 35)
                .addGroup(panelButtonLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnXoaBo)
                    .addComponent(btnLuuLai)
                    .addComponent(btnThemMoi))
                .addContainerGap())
        );

        jSplitPane1.setLeftComponent(panelButton);

        tableLoaiDaiLy.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        tableLoaiDaiLy.setEditable(false);
        tableLoaiDaiLy.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tableLoaiDaiLyMouseClicked(evt);
            }
        });
        tableLoaiDaiLy.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                tableLoaiDaiLyKeyPressed(evt);
            }
        });
        jScrollPane2.setViewportView(tableLoaiDaiLy);

        txtStatus.setFont(new java.awt.Font("sansserif", 1, 12)); // NOI18N
        txtStatus.setForeground(new java.awt.Color(0, 0, 204));

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 248, Short.MAX_VALUE)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addComponent(txtStatus)
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 556, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(txtStatus))
        );

        txtStatus.getAccessibleContext().setAccessibleName("txtStatus");

        jSplitPane1.setRightComponent(jPanel2);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jSplitPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 600, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jSplitPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 588, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents
    
    //<editor-fold defaultstate="collapsed" desc="implements interface IInitGUI">
    /*Khởi tạo các giá trị cơ bản*/
    @Override
    public void initCustom() {
        initState();
        initTable();
        initKeyBoards();
    }
    
    /*Khởi tạo các tổ hợp phím*/
    @Override
    public void initKeyBoards() {  
       btnLuuLai.setMnemonic(KeyEvent.VK_S);
       btnLuuLai.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_S, InputEvent.CTRL_DOWN_MASK), "luulai");
       btnLuuLai.getActionMap().put("luulai", 
               new AbstractAction() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        handleLuuLaiButton();
                    }                   
               });
       
       /*Thêm phím tắt cho thêm mới*/
       btnThemMoi.setMnemonic(KeyEvent.VK_N);
       btnThemMoi.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_N, InputEvent.CTRL_DOWN_MASK), "themmoi");
       btnThemMoi.getActionMap().put("themmoi",
               new AbstractAction() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        handleThemMoiButton();
                    }                   
               });
       
       /*Thêm phím tắt cho xóa*/
       btnXoaBo.setMnemonic(KeyEvent.VK_DELETE);
       btnXoaBo.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, InputEvent.CTRL_DOWN_MASK), "xoabo");
       btnXoaBo.getActionMap().put("xoabo",
               new AbstractAction() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        handleXoaBoButton();
                    }                   
               });
    }
    
    /*Khởi tạo bảng*/
    @Override
    public void initTable() {
        tableLoaiDaiLy.setModel(LoaiDaiLyBUS.getTableModel());
    }
    
    /*Khởi tạo trạng thái*/
    @Override
    public void initState() {
        setSuspendedState();
        setRefreshState();
    }
    //</editor-fold>
    
    //<editor-fold defaultstate="collapsed" desc="Kiểm tra các ô input">
    /*Kiểm tra các ô input*/
    private boolean checkAllField() {
        return ( checkTXTTenLoaiDaiLy()  && checkTXTMaLoaiDaiLy());
        // Giao các kết quả
    }
    
    private boolean checkTXTMaLoaiDaiLy() {
        if (txtMaLoaiDaiLy.getText().isEmpty()) {
            // trường hợp mã quận trống
            txtMaLoaiDaiLy_Error.setText(ErrorMessages.LOAIDAILYGUI_TXTMALOAIDAILY_ERROR_EMPTY);
            return false;
        } else if (txtMaLoaiDaiLy.getText().length() < GUIConstant.LOAIDAILY_MALOAIDAILY_LENGTH_MIN) {
            // trường hợp mã quận nhỏ hơn giá trị nhỏ nhất
            txtMaLoaiDaiLy_Error.setText(ErrorMessages.LOAIDAILYGUI_TXTMALOAIDAILY_ERROR_LESS +
                    GUIConstant.LOAIDAILY_MALOAIDAILY_LENGTH_MIN);
            return false;
        } else if (txtMaLoaiDaiLy.getText().length() > GUIConstant.LOAIDAILY_MALOAIDAILY_LENGTH_MAX) {
            // trường hợp lớn hon giá trị cho phép
            txtMaLoaiDaiLy_Error.setText(ErrorMessages.LOAIDAILYGUI_TXTMALOAIDAILY_ERROR_GREATER + 
                    GUIConstant.LOAIDAILY_MALOAIDAILY_LENGTH_MAX);
        } else if (!checkExistMaLoaiDaiLy()){
            // Nếu mã quận đã tồn tại
            txtMaLoaiDaiLy_Error.setText(ErrorMessages.LOAIDAILYGUI_TXTMALOAIDAILY_ERROR_EXIST);
            return false;
        } else {
            txtMaLoaiDaiLy_Error.setText("");
        }
        
        return true;
    }
    
    /*Kiểm tra mã quận có tồn tại hay không*/
    private boolean checkExistMaLoaiDaiLy() {
        return LoaiDaiLyBUS.checkMaLoaiDaiLy(txtId.getText(),
                                        txtMaLoaiDaiLy.getText()
                                        );
    }

    /*Kiểm tra tính hợp lệ của các ô nhập liệu tên quận*/
    private boolean checkTXTTenLoaiDaiLy() {
        if (txtTenLoaiDaiLy.getText().isEmpty()) {
            //Trường hợp ô tên quận bị bỏ trống
            txtTenLoaiDaiLy_Error.setText(ErrorMessages.LOAIDAILYGUI_TXTLOAIDAILY_ERROR_NONE);
            return false;
        } else if (txtTenLoaiDaiLy.getText().length() < GUIConstant.LOAIDAILY_TEN_LENGHT_MIN) {
            //Trường hợp tên quân quá ngắn
            txtTenLoaiDaiLy_Error.setText(ErrorMessages.LOAIDAILYGUI_TXTLOAIDAILY_ERROR_LESS + 
                                  GUIConstant.LOAIDAILY_TEN_LENGHT_MIN
                                  );
            return false;
        } else if (txtTenLoaiDaiLy.getText().length() > GUIConstant.LOAIDAILY_TEN_LENGHT_MAX) {
            //Trường hợp tên quận quá dài
            txtTenLoaiDaiLy_Error.setText(ErrorMessages.LOAIDAILYGUI_TXTLOAIDAILY_ERROR_GREATER_THAN +
                    GUIConstant.LOAIDAILY_TEN_LENGHT_MAX);
            return false;
        } else {
            txtTenLoaiDaiLy_Error.setText("");
            return true;
        }
    }
    
    //</editor-fold>
    
    //<editor-fold defaultstate="collapsed" desc="implements IStateGUI">
    /*Refesh state*/
    @Override
    public void setRefreshState() {
        
    }
    
    /*Trạng thái khởi động form*/
    @Override
    public void setSuspendedState() {
        currState = LoaiDaiLyGUIState.SUSPENDED;
        setEnabledState(false);
        btnLuuLai.setEnabled(false);
        btnXoaBo.setEnabled(false);
        btnThemMoi.setEnabled(true);
        txtStatus.setText(StatusMessage.SUSPENDED_STATE);
    }
    
    /*Trạng thái thêm một record mới*/
    @Override
    public void setCreationalState() {
        currState = LoaiDaiLyGUIState.CREATIONAL;
        setEnabledState(true);
        btnLuuLai.setEnabled(true);
        btnXoaBo.setEnabled(false);
        btnThemMoi.setEnabled(true);
        
        //Cập nhật các textfield
        txtId.setText(String.valueOf(LoaiDaiLyBUS.getNewMaLoaiDaiLy()));
        txtTenLoaiDaiLy.requestFocus();
        txtTenLoaiDaiLy.setText("");
        txtMoTa.setText("");
        txtMaLoaiDaiLy.setText("");
        
        txtStatus.setText(StatusMessage.CREATIONAL_STATE);
    }
    
    /*Trạng thái khi một record trong bảng được chọn*/
    @Override
    public void setSelectionState() {
        currState = LoaiDaiLyGUIState.EDITABLE;
        setEnabledState(true);
        btnLuuLai.setEnabled(true);
        btnXoaBo.setEnabled(true);
        btnThemMoi.setEnabled(true);
        
        txtStatus.setText(StatusMessage.SELECTION_STATE);
    }
    
    /*Thiết lập trạng thái enable của các control*/
    @Override
    public void setEnabledState(boolean flag) {
        txtMaLoaiDaiLy.setEnabled(flag);
        txtMoTa.setEnabled(flag);
        txtTenLoaiDaiLy.setEnabled(flag);
        txtId.setEnabled(flag);
    }
    
    //</editor-fold>
        
    //<editor-fold defaultstate="collapsed" desc="implement ITableGUI Interface">
    /*Hiển thị thông tin*/
    @Override
    public void sendDataFromSelectedRecordOfTableToField() {
        int row = tableLoaiDaiLy.getSelectedRow(); // Lấy chỉ số hàng hiện tại được chọn
        if (row < 0) return;
        //Tải thông tin lên các control hiển thị
        String maloaidaily = LoaiDaiLyBUS.getValue(   
                                            tableLoaiDaiLy.getModel(), 
                                            row, 
                                            LoaiDaiLyDTO.MA_LOAI_DAI_LY
                                                   ).toString();      
        String tenloaidaily = LoaiDaiLyBUS.getValue(
                                            tableLoaiDaiLy.getModel(),
                                            row, 
                                            LoaiDaiLyDTO.TEN_LOAI_DAI_LY
                                                    ).toString();
        String mota  = LoaiDaiLyBUS.getValue(
                                       tableLoaiDaiLy.getModel(),
                                       row,
                                       LoaiDaiLyDTO.MO_TA
                                             ).toString();
        String sodinhdanh = LoaiDaiLyBUS.getValue(
                                          tableLoaiDaiLy.getModel(),
                                          row, 
                                          LoaiDaiLyDTO.ID
                                                  ).toString();
        

        txtMaLoaiDaiLy.setText(maloaidaily);
        txtTenLoaiDaiLy.setText(tenloaidaily);
        txtId.setText(sodinhdanh);
        txtMoTa.setText(mota);
    }
    
    /*Cập nhật thông tin từ field lên bảng*/
    @Override
    public void sendDataFromFieldToSelectedRecordOfTable() {
        int row = tableLoaiDaiLy.getSelectedRow();
        if (row < 0) return;
        
        String sodinhdanh = txtId.getText();
        String maloaidaily = txtMaLoaiDaiLy.getText();
        String tenloaidaily = txtTenLoaiDaiLy.getText();
        String mota = txtMoTa.getText();
        
        LoaiDaiLyBUS.setValue(tableLoaiDaiLy.getModel(),
                row,
                LoaiDaiLyDTO.ID,
                sodinhdanh
                );
        
        LoaiDaiLyBUS.setValue(tableLoaiDaiLy.getModel(),
                row,
                LoaiDaiLyDTO.MA_LOAI_DAI_LY,
                maloaidaily
                );
        LoaiDaiLyBUS.setValue(tableLoaiDaiLy.getModel(),
                row,
                LoaiDaiLyDTO.MO_TA,
                mota
                );
        LoaiDaiLyBUS.setValue(tableLoaiDaiLy.getModel(),
                row,
                LoaiDaiLyDTO.TEN_LOAI_DAI_LY,
                tenloaidaily
                );
    }
    
    /**
     * Chuyển dữ liệu từ field lên table
     */
    @Override
    public void sendDataFromFieldToNewRecordOfTable() {
        String sodinhdanh = txtId.getText();
        String maloaidaily = txtMaLoaiDaiLy.getText();
        String tenloaidaily = txtTenLoaiDaiLy.getText();
        String mota = txtMoTa.getText();
        
        ((DefaultTableModel)tableLoaiDaiLy.getModel()).addRow(new Object[] {
           sodinhdanh, 
           maloaidaily,
           tenloaidaily,
           mota
        });
    }
    
    //</editor-fold>
    
    //<editor-fold defaultstate="collapsed" desc="implement interface IDATAGUI">
    @Override
    public boolean insertRecord() {
        String sodinhdanh, maloaidaily, tenloaidaily, mota;
       
        // Thêm thông tin vào database
       sodinhdanh = txtId.getText();
       maloaidaily = txtMaLoaiDaiLy.getText();
       tenloaidaily = txtTenLoaiDaiLy.getText();
       mota = txtMoTa.getText();
       return LoaiDaiLyBUS.insertRecord(sodinhdanh, maloaidaily,
                                        tenloaidaily, mota);
    }
    
    @Override
    public boolean deleteRecord() {
  
        return LoaiDaiLyBUS.deleteRecord(txtId.getText()); // xoá quận khỏi danh sách dựa vào mã quận
    }
    
    @Override
    public boolean updateRecord() {
       
        return LoaiDaiLyBUS.updateRecord(
                txtId.getText(),
                txtMaLoaiDaiLy.getText(), 
                txtTenLoaiDaiLy.getText(),
                txtMoTa.getText()
                ); // Cập nhật xuống database   
    }
    //</editor-fold>
    
    /*Cập nhật thông báo trạng thái*/
    public void setStatus(String status) {
        txtStatus.setText(status);
    }
    
    private void txtTenLoaiDaiLyFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtTenLoaiDaiLyFocusLost
        checkTXTTenLoaiDaiLy(); // Kiểm tra tính hợp lệ của ô tên quận
        txtMaLoaiDaiLy.setText(ToolOfGUI.getFirstCharsOfString(txtTenLoaiDaiLy.getText()));
    }//GEN-LAST:event_txtTenLoaiDaiLyFocusLost

    private void txtMaLoaiDaiLyKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtMaLoaiDaiLyKeyTyped

    }//GEN-LAST:event_txtMaLoaiDaiLyKeyTyped

    private void btnThemMoiActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnThemMoiActionPerformed
        handleThemMoiButton();
    }//GEN-LAST:event_btnThemMoiActionPerformed

    private void btnXoaBoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnXoaBoActionPerformed
        handleXoaBoButton();
    }//GEN-LAST:event_btnXoaBoActionPerformed

    private void tableLoaiDaiLyMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tableLoaiDaiLyMouseClicked
        handleTableSelected();
    }//GEN-LAST:event_tableLoaiDaiLyMouseClicked

    private void btnLuuLaiActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnLuuLaiActionPerformed
        handleLuuLaiButton();
    }//GEN-LAST:event_btnLuuLaiActionPerformed

    private void tableLoaiDaiLyKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_tableLoaiDaiLyKeyPressed
       handleTableSelected();
    }//GEN-LAST:event_tableLoaiDaiLyKeyPressed

    private void txtMaLoaiDaiLyFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtMaLoaiDaiLyFocusLost
        checkTXTMaLoaiDaiLy();
    }//GEN-LAST:event_txtMaLoaiDaiLyFocusLost
        //</editor-fold>
    
    //<editor-fold defaultstate="collapsed" desc="Handle of Event">
  
    
    /**
     * Thực thi xử lí sự kiện table được chọn
     */
    private void handleTableSelected() {
        if (tableLoaiDaiLy.getSelectedRow() < 0) return;
        setSelectionState();
        sendDataFromSelectedRecordOfTableToField(); //Chuyển thông tin từ table lên các ô thông tin 
    }
    
    /*Thực thi nút Lưu lại*/
    private void handleLuuLaiButton() {
        if (currState == LoaiDaiLyGUIState.SUSPENDED) return;
        // Nếu như đang ở trạng thái tạo mới thì insert record mới
        if (!checkAllField()) return;
        if (currState == LoaiDaiLyGUIState.CREATIONAL) { // đang ở trạng thái tạo mới
            if (insertRecord()) {                  
                txtStatus.setText(StatusMessage.SUCCESS_SAVE);
                // Cập nhật thông tin bảng hiển thị
                sendDataFromFieldToNewRecordOfTable();
                setCreationalState();
            } else {
                txtStatus.setText(StatusMessage.FAIL_SAVE);
            }
        } else if (currState == LoaiDaiLyGUIState.EDITABLE) { // đang ở trạng thái cập nhật
            if (updateRecord()) {
                txtStatus.setText(StatusMessage.SUCCESS_UPDATE);
                sendDataFromFieldToSelectedRecordOfTable();
            } else {
                txtStatus.setText(StatusMessage.FAIL_UPDATE);
            }
        }
    }
    
    /*Thực thi xử lí tổ hợp phím*/
    private void handleKeyPress(KeyEvent evt) {
          if ((evt.getModifiers() & KeyEvent.CTRL_DOWN_MASK)!= 0) {
            switch (evt.getKeyCode()) {
                case KeyEvent.VK_S: handleLuuLaiButton(); break;
            }
        }
    }
    
    /*Thực thi xử lí thêm mới*/
    private void handleThemMoiButton() {
        setCreationalState();
    }
    
    /*Thực thi xóa bỏ*/
    private void handleXoaBoButton() {
        if (deleteRecord()) {
            txtStatus.setText(StatusMessage.SUCCESS_UPDATE);
        //Xóa thông tin khỏi bảng hiển thị
            ((DefaultTableModel)tableLoaiDaiLy.getModel()).removeRow(tableLoaiDaiLy.getSelectedRow());
            setCreationalState();
        } else {
            txtStatus.setText(StatusMessage.FAILT_DELETE);
        }
    } 
    //</editor-fold>
    
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(LoaiDaiLyGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(LoaiDaiLyGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(LoaiDaiLyGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(LoaiDaiLyGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new LoaiDaiLyGUI().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnLuuLai;
    private javax.swing.JButton btnThemMoi;
    private javax.swing.JButton btnXoaBo;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JSplitPane jSplitPane1;
    private javax.swing.JPanel panelButton;
    private org.jdesktop.swingx.JXTable tableLoaiDaiLy;
    private javax.swing.JTextField txtId;
    private javax.swing.JTextField txtMaLoaiDaiLy;
    private javax.swing.JLabel txtMaLoaiDaiLy_Error;
    private javax.swing.JTextArea txtMoTa;
    private javax.swing.JLabel txtStatus;
    private javax.swing.JTextField txtTenLoaiDaiLy;
    private javax.swing.JLabel txtTenLoaiDaiLy_Error;
    // End of variables declaration//GEN-END:variables

}
enum LoaiDaiLyGUIState {
    SUSPENDED,
    CREATIONAL,
    EDITABLE
}